package com.ak.server.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ak.common.entity.QueryRequest;
import com.ak.common.entity.constant.PageConstant;
import com.ak.common.entity.system.Dept;
import com.ak.common.enums.Enums;
import com.ak.common.utils.TreeUtil;
import com.ak.server.system.mapper.DeptMapper;
import com.ak.server.system.service.IDeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("deptService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    @Override
    public Map<String, Object> findDepts(QueryRequest request, Dept dept) {
        Map<String, Object> result = new HashMap<>(2);
        try {
            List<Dept> depts = findDepts(dept, request);
            List<Dept> trees = new ArrayList<Dept>();
            buildTrees(trees, depts);
            List<Dept> deptTree = TreeUtil.buildTree(trees);

            result.put(PageConstant.ROWS, deptTree);
            result.put(PageConstant.TOTAL, depts.size());
        } catch (Exception e) {
            log.error("获取部门列表失败", e);
            result.put(PageConstant.ROWS, null);
            result.put(PageConstant.TOTAL, 0);
        }
        return result;
    }

    @Override
    public List<Dept> findDepts(Dept dept, QueryRequest request) {
    	LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<Dept>();
        if (StringUtils.isNotBlank(dept.getDeptName())) {
            queryWrapper.like(Dept::getDeptName, dept.getDeptName());
        }
        queryWrapper.eq(Dept::getDelFlag, Enums.DelFlag.EXIST.getCode());
        queryWrapper.orderByAsc(Dept::getSort);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createDept(Dept dept) {
        if (dept.getParentId() == null) {
            dept.setParentId(Dept.TOP_DEPT_ID);
        }
        dept.setCreateTime(new Date());
        this.save(dept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDept(Dept dept) {
        if (dept.getParentId() == null) {
            dept.setParentId(Dept.TOP_DEPT_ID);
        }
        dept.setUpdateTime(new Date());
        this.baseMapper.updateById(dept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDepts(Integer[] deptIds) {
        this.delete(Arrays.asList(deptIds));
    }

    private void buildTrees(List<Dept> trees, List<Dept> depts) {
        depts.forEach(dept -> {
            Dept tree = new Dept();
            tree.setId(dept.getDeptId());
            tree.setParentId(dept.getParentId());
            tree.setLabel(dept.getDeptName());
            tree.setSort(dept.getSort());
            trees.add(tree);
        });
    }

    private void delete(List<Integer> deptIds) {
        removeByIds(deptIds);

        LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dept::getParentId, deptIds);
        List<Dept> depts = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(depts)) {
            List<Integer> deptIdList = new ArrayList<Integer>();
            depts.forEach(d -> deptIdList.add(d.getDeptId()));
            this.delete(deptIdList);
        }
    }

}
